//
//  TimeViewController.m
//  Run
//
//  Created by sxz on 16/4/11.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "TimeViewController.h"
#import "KACircleProgressView.h"
#import "AlarmClockViewController.h"
#import "CoreDataManager.h"
#import "TimeData.h"
#import "TimePlanTableViewCell.h"
#import "WeekCollectionViewCell.h"
@interface TimeViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign ) CGFloat qq;
@property (nonatomic, strong) UILabel *times;//时间
@property (nonatomic, strong) UILabel *day;//日期
@property (nonatomic, strong) UILabel *weekDay;//周几
@property (nonatomic, strong) NSTimer *timer;//计时器


@property (nonatomic, strong) NSDate *currentDate;
@property (nonatomic, strong) NSArray *arrWeek;
@property (nonatomic, strong) NSDateComponents *comps;
@property (nonatomic, strong) NSString *second;
@property (nonatomic, strong) NSMutableArray *timeDataSource;
@property (nonatomic, strong) CoreDataManager *coreDataManager;//数据
@property (nonatomic, strong) UIView *timeView;//表盘View
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation TimeViewController
- (void)viewWillAppear:(BOOL)animated {
    [self reloop];
    self.qq = (_comps.second)* 10;
    [self selectData];
//    [_colorView startAnimation];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor grayColor];
    
    self.timeDataSource = [NSMutableArray arrayWithCapacity:0];
    
    self.coreDataManager = [CoreDataManager shareCoreDataManager];

//    定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(reloop) userInfo:nil repeats:YES];
    self.qq = (_comps.second) * 10;
    
    self.arrWeek = [NSArray array];
    self.arrWeek = @[@"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六"];
    
    
    //    表盘View
    
    self.timeView = [UIView new];
    _timeView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.timeView];
    
    [self.timeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).offset(-120);
        make.size.mas_equalTo(CGSizeMake(250* SCALEWIDTH , 250* SCALEWIDTH ));
    }];
    
    
    
//    画圆
    KACircleProgressView *progress = [[KACircleProgressView alloc] init];
   
    [self.timeView addSubview:progress];
    
    [progress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).offset(-120);
        make.size.mas_equalTo(CGSizeMake(250* SCALEWIDTH, 250* SCALEWIDTH));
    }];
    progress.tag = 1000;
    progress.trackColor = [UIColor colorWithRed:1.000 green:0.435 blue:0.812 alpha:1.000];//圆环背景颜色
    progress.progressColor = [UIColor cyanColor];//划线颜色
    progress.progressWidth = 5;
    
//    设置圆形
    [_timeView.layer setCornerRadius:250 * SCALEWIDTH / 2];
    _timeView.layer.masksToBounds = YES;
    _timeView.layer.borderWidth = 2 * SCALEHEIGHT;
    _timeView.layer.borderColor = [[UIColor colorWithRed:1.000 green:1.000 blue:0.400 alpha:1.000] CGColor];


    
    //时间
    self.times = [UILabel new];
    _times.textAlignment = NSTextAlignmentCenter;
    _times.font = [UIFont systemFontOfSize:35];
    [_timeView addSubview:_times];
    
    [_times mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_timeView.mas_top).offset(65 * SCALEHEIGHT);
        make.centerX.equalTo(_timeView.mas_centerX);
        make.height.equalTo(@50);
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
    }];
    
    self.day = [UILabel new];
    _day.textAlignment = NSTextAlignmentCenter;
    [_timeView addSubview:_day];
    
    
    [_day mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_times.mas_top).offset(50 * SCALEWIDTH);
        make.centerX.equalTo(_timeView.mas_centerX);
        make.height.equalTo(@50);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
    }];
    
    
    self.weekDay = [UILabel new];
    _weekDay.textAlignment = NSTextAlignmentCenter;
    [_timeView addSubview:_weekDay];
    
    [_weekDay mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_day.mas_top).offset(45 * SCALEWIDTH);
        make.centerX.equalTo(_timeView.mas_centerX);
        make.height.equalTo(@50);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
    }];
    
    [self creatTableView];
    
    [self selectData];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"闹钟" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    
    


    
}
- (void)buttaonAction:(UIButton *)sender {
    AlarmClockViewController *ACVC = [[AlarmClockViewController alloc] init];
    
    [self presentViewController:ACVC animated:YES completion:^{
        
    }];
}


//闹钟点击
- (void)rightAction:(id)sender {
    
    if (self.timeDataSource.count < 10) {
        
        AlarmClockViewController *addTimeVC = [[AlarmClockViewController alloc] init];
        
        addTimeVC.todayWeek = _weekDay.text;
        
        [self.navigationController pushViewController:addTimeVC animated:YES];
        
        self.navigationController.navigationBarHidden =YES;
        
        self.navigationController.tabBarController.tabBar.hidden = YES;
        
    } else {
        
        UIAlertView *alartView = [[UIAlertView alloc]initWithTitle:nil message:@"闹钟数量已经达到上限" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alartView show];
    }
}


- (void)reloop {
    //   画圆
    KACircleProgressView *progress = [self.view viewWithTag:1000];
    progress.progress = _qq / 600;
    
    self.currentDate = [NSDate date];//获取当前时间，日期
   
    
    NSDateFormatter *dateFormatterDay = [[NSDateFormatter alloc] init];
    //    格式
    [dateFormatterDay setDateFormat:@"YYYY-MM-dd"];
    
    //    获取日期
    NSString *Day = [dateFormatterDay stringFromDate:_currentDate];
    
   
   
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    
    self.comps = [[NSDateComponents alloc] init] ;
    
    NSInteger unitFlags = NSCalendarUnitWeekday | NSCalendarUnitHour |
    NSCalendarUnitMinute |
    NSCalendarUnitSecond;
    
    //    转格式
    _comps = [cal components:unitFlags fromDate:_currentDate];
    
    
    NSInteger week = _comps.weekday;
    NSString *hour = [NSString stringWithFormat:@"%ld", _comps.hour];
    
    NSString *minute = [NSString stringWithFormat:@"%ld", _comps.minute];
    self.second = [NSString stringWithFormat:@"%ld", _comps.second];
    
    
    if (_comps.hour < 10) {
        hour = [NSString stringWithFormat:@"0%ld", _comps.hour];
    }
    if (_comps.minute < 10) {
        minute = [NSString stringWithFormat:@"0%ld", _comps.minute];
    }
    if (_comps.second < 10) {
        self.second = [NSString stringWithFormat:@"0%ld", _comps.second];
    }
    
    _qq += 1;
    if (_qq >= 600) {
        _qq = 0;
    }
    //    赋值
    self.times.text = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, self.second];
   
    
    self.day.text = Day;

    
    self.weekDay.text = [NSString stringWithFormat:@"%@", [_arrWeek objectAtIndex:week - 1]];
    

    
}





#pragma mark selectData
- (void)selectData {
    
//    查询
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"TimeData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    }else{
        
        self.timeDataSource = [NSMutableArray arrayWithArray:fetchedObjects];
    }
    
    [self.tableView reloadData];
    
}

#pragma mark TableViewCreat
- (void)creatTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    _tableView.backgroundColor = [UIColor colorWithWhite:0.400 alpha:1.000];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
        make.height.offset(160 * SCALEHEIGHT);
        make.bottom.equalTo(@-69);
    }];
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return  UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
//    如果是一周 走这个方法
    TimeData *timer = self.timeDataSource[indexPath.row];
    
    NSString *time = [NSString stringWithFormat:@"%@-%@-%@", timer.hour, timer.minte, timer.week];
    
    if (timer.week.length == 21) {
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *myArray = [app scheduledLocalNotifications];
        
        
        
        for (int i = 0; i < myArray.count; i++) {
            UILocalNotification * myUILocalNotification=[myArray objectAtIndex:i];
            
            if ([[[myUILocalNotification userInfo] objectForKey:time] isEqualToString:time]) {
                [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
            }
            
        }
        
    } else {
//        不是一周
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *myArray = [app scheduledLocalNotifications];
        
        for (int i = 0; i < timer.week.length / 3; i++) {
            NSString *string = [timer.week substringWithRange:NSMakeRange(i * 3, 3)];
            for (int j = 0; j < myArray.count; j++) {
                UILocalNotification * myUILocalNotification=[myArray objectAtIndex:j];
                
                if ([[[myUILocalNotification userInfo] objectForKey:[NSString stringWithFormat:@"%@-%@", timer.week, string]] isEqualToString:[NSString stringWithFormat:@"%@-%@", time, string]]) {
                    [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
                }
                
            }
            
        }
        
    }
    
    [self.coreDataManager.managedObjectContext deleteObject:timer];
    
    [self.coreDataManager saveContext];//保存
    
    [self.timeDataSource removeObjectAtIndex:indexPath.row];
    
    [self.tableView reloadData];
}

#pragma marl TableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.timeDataSource.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80 * SCALEHEIGHT;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TimePlanTableViewCell *cell = [[TimePlanTableViewCell alloc] init];
    
    cell.timer = self.timeDataSource[indexPath.row];
    
    cell.backgroundColor = [UIColor colorWithWhite:0.298 alpha:1.000];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
